from datetime import datetime
from app.Pojo.BClassification import BClassification
from app.Mapper.ClassificationMapper  import ClassificationMapper
from app.Utils.exceptions import BusinessException


class ClassificationService:
    def __init__(self, db):
        self.mapper = ClassificationMapper(db)

    def list_classifications(self, page, page_size):
        """分页查询分类"""
        classifications, total = self.mapper.list_classifications(page, page_size)
        return {
            'total': total,
            'page': page,
            'pageSize': page_size,
            'list': [
                {
                    'id': c.id,
                    'pid': c.pid,
                    'title': c.title,
                    'create_time': c.create_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                for c in classifications
            ]
        }

    def create_classification(self, data):
        """新增分类"""
        title = data.get('title')
        if not title:
            raise BusinessException(400, "缺少必要参数: title")

        pid = data.get('pid', 0)

        # 检查父分类是否存在（如果不为0）
        if pid != 0:
            parent = self.mapper.get_by_id(pid)
            if not parent:
                raise BusinessException(400, "父分类不存在")

        classification = BClassification(
            title=title,
            pid=pid,
            create_time=datetime.utcnow()
        )

        result = self.mapper.create_classification(classification)

        return {
            'id': result.id,
            'pid': result.pid,
            'title': result.title,
            'create_time': result.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def get_classification(self, id):
        """查询回显"""
        classification = self.mapper.get_by_id(id)
        if not classification:
            raise BusinessException(404, "分类不存在")

        return {
            'id': classification.id,
            'pid': classification.pid,
            'title': classification.title,
            'create_time': classification.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def update_classification(self, id, data):
        """修改分类"""
        classification = self.mapper.get_by_id(id)
        if not classification:
            raise BusinessException(404, "分类不存在")

        title = data.get('title')
        pid = data.get('pid')

        if title is not None:
            classification.title = title

        if pid is not None:
            # 检查父分类是否存在（如果不为0）
            if pid != 0:
                parent = self.mapper.get_by_id(pid)
                if not parent:
                    raise BusinessException(400, "父分类不存在")
            classification.pid = pid

        result = self.mapper.update_classification(classification)

        return {
            'id': result.id,
            'pid': result.pid,
            'title': result.title,
            'create_time': result.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': result.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def delete_classifications(self, ids):
        """删除分类"""
        if not ids:
            raise BusinessException(400, "缺少必要参数: ids")

        # 检查分类是否存在
        for id in ids:
            classification = self.mapper.get_by_id(id)
            if not classification:
                raise BusinessException(404, f"分类ID {id} 不存在")

        self.mapper.delete_classifications(ids)

    def delete_classification(self, id):
        """删除分类"""
        classification = self.mapper.get_by_id(id)
        if not classification:
            raise BusinessException(404, "分类不存在")

        self.mapper.delete_classification(id)